
function SQL(content) {
    this.pre = null;
    this.content = content;
    this.next = null;
}

function LinkNode(node1, node2) {
    node1.next = node2
    node2.pre = node1
}

var hashSet = new Set()

var headSQL = new SQL('');
var middleSQL = new SQL('');
var tailSQL = new SQL('');
LinkNode(headSQL, middleSQL)
LinkNode(middleSQL, tailSQL)
LinkNode(tailSQL, headSQL)


var currentSQL = headSQL

// 拦截请求
chrome.webRequest.onBeforeRequest.addListener(
    function (info) {

        if (info.requestBody && info.requestBody.raw) {
            info.requestBody.raw = info.requestBody.raw.map(function (part) {
                if (part.bytes) {
                    part.bytes = [].slice.call(
                        new Uint8Array(part.bytes.slice(0, 500e3)));
                }
                return part;
            });
        }
        var bytesView = new Uint8Array(info.requestBody.raw[0].bytes);
        var request_body = new TextDecoder().decode(bytesView);
        var sql = JSON.parse(request_body).sql
        // sqls = sql
        // chrome.tabs.sendMessage(info.tabId, info);
        if (sql) {
            var hash = hex_md5(sql.replace(/\s+/g, ''));
            if (!hashSet.has(hash)) {
                hashSet.add(hash);
                var current_content = currentSQL.content
                if (current_content) {
                    hashSet.delete(hex_md5(current_content.replace(/\s+/g, '')))
                }
                currentSQL.content = sql;
                hashSet.add(hash);
                currentSQL = currentSQL.next;
            }
        }
    },
    { urls: ["https://sqlaudit.xrxr.xyz/api/v1/search"] },
    ["requestBody"]
);

function getSQL() {
    var sqls = []
    var current = currentSQL.pre
    while (current.content && sqls.length < 3) {
        sqls.push(current.content);
        current = current.pre;
    }
    return sqls;
}

function sendSQL(text) {
    sendMessageToContentScript(text)
}

// 获取当前选项卡ID
function getCurrentTabId(callback) {
    chrome.tabs.query({ url: '*://sqlaudit.xrxr.xyz/*' }, (tabs) => {
        callback(tabs)
    });
}

function sendMessageToContentScript(message) {
    chrome.windows.getCurrent((current) => {
        getCurrentTabId((tabs) => {
            for (var i = 0; i < tabs.length; i++) {
                if (tabs[i].url == "https://sqlaudit.xrxr.xyz/#/querypage" && tabs[i].active && tabs[i].windowId == current.id) {
                    chrome.tabs.sendMessage(tabs[i].id, message);
                }
            }
        });
    })
}
